<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="userName">
      <el-input v-model="loginForm.userName" placeholder="请输入用户名">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="loginPwd">
      <el-input v-model="loginForm.loginPwd" type="password" placeholder="请输入密码" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="verificationCode" v-if="isOpenVerificationCode">
      <el-row :gutter="20" class="verification-code-row">
        <el-col :span="18" class="verification-code-row-input">
          <el-input v-model="loginForm.verificationCode" placeholder="请输入验证码">
            <template #prefix>
              <el-icon class="el-input__icon">
                <Key />
              </el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6" class="verification-code-row-image" @click="getVerifyCode()">
          <el-image class="image" :src="imageSrc" fit="fit" />
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item prop="rememberPassword">
      <el-row :gutter="20" class="verification-code-row">
        <el-col :span="18" class="verification-code-row-input">
          <el-checkbox v-model="rememberPassword" label="记住密码" size="large" />
        </el-col>
        <el-col :span="6" class="verification-code-row-image">
          <el-link type="primary">忘记密码</el-link>
        </el-col>
      </el-row>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button round size="large" type="primary" :loading="loading" @click="login(loginFormRef)"> 登录 </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, UnwrapRef, Ref } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { Login, SystemConfig } from "@/api/interface";
import { ElNotification } from "element-plus";
import { loginApi, loginUserApi, verifyCodeApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import type { ElForm } from "element-plus";
import { systemConfigApi } from "@/api/common";
import md5 from "md5";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  loginPwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
  verificationCode: [{ required: true, message: "请输入验证码", trigger: "blur" }]
});

const loading = ref(false);
const rememberPassword = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  userName: "admin",
  loginPwd: "12345678",
  verificationCode: "",
  verificationCodeKey: ""
});
const imageSrc: Ref<UnwrapRef<string>> = ref("");
const isOpenVerificationCode: Ref<UnwrapRef<Boolean>> = ref(false);
const configKey = reactive<SystemConfig.ResConfigKey>({
  configKey: "isOpenVerificationCode"
});
const getVerifyCode = async () => {
  const configValue = await systemConfigApi(configKey);
  if (configValue && configValue == "Y") {
    isOpenVerificationCode.value = true;
    const { verificationCode, verificationCodeKey, imageData } = await verifyCodeApi();
    loginForm.verificationCodeKey = verificationCodeKey;
    loginForm.verificationCode = verificationCode;
    imageSrc.value = imageData;
  }
};
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const data = await loginApi({ ...loginForm, loginPwd: md5(loginForm.loginPwd) });
      userStore.setToken(data);
      const { userId, roles, name, avatar, realName, mobile } = await loginUserApi();
      const userInfo = {
        userId: userId,
        roles: roles,
        name: name,
        avatar: avatar,
        realName: realName,
        mobile: mobile
      };
      userStore.setUserInfo(userInfo);
      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      await tabsStore.closeMultipleTab();
      await keepAliveStore.setKeepAliveName();

      // 4.跳转到首页
      await router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录 Geeker-Admin",
        type: "success",
        duration: 3000
      });
    } finally {
      loading.value = false;
      await getVerifyCode();
    }
  });
};

onMounted(() => {
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
  getVerifyCode();
});
</script>

<style scoped lang="scss">
@import "../index.scss";

.verification-code-row {
  width: 100% !important;
  margin-left: 0 !important;
}
.verification-code-row-input {
  padding-left: 0 !important;
}
.verification-code-row-image {
  padding-right: 0 !important;
  .image {
    height: 40px;
    display: flex;
    width: 100%;
  }
}
.el-icon-safe {
  background: url(../../../assets/images/safe.png) center no-repeat;
  background-size: 55% 35%;
  color: black;
}
</style>
